package com.basic.ui.utils

import android.view.View

/**
 * @author Peter Liu
 * @since 2023/7/21 00:46
 *
 */
object ClickLimiter {
    const val INTERVAL = 400

    private var lastClickTime: Long = 0

    fun isFastClick(spaceTime: Int = INTERVAL): Boolean {
        val currentTime = System.currentTimeMillis()
        var offset = spaceTime
        if (offset <= 0) {
            offset = INTERVAL
        }
        val isFastClick: Boolean = currentTime - lastClickTime <= offset
        if (!isFastClick) {
            lastClickTime = currentTime
        }
        return isFastClick
    }
}

typealias OnViewClick = (View) -> Unit

inline fun View.setOnClick(
    interval: Int = ClickLimiter.INTERVAL,
    crossinline onClick: OnViewClick
) {
    setOnClickListener {
        if (!ClickLimiter.isFastClick(interval)) {
            onClick.invoke(it)
        }
    }
}